﻿using MultiLang;
using System;

using JetBrains.Annotations;
using Rsdn.SmartApp;

namespace Rsdn.Janus
{
	[ActivePart]
	public class SyncNotificationActivePart : ActivePartBase
	{
		private readonly ISynchronizer _synchronizer;
		private IDisposable _startSyncSubscription;
		private IDisposable _endSyncSubscription;

		public SyncNotificationActivePart([NotNull] IServiceProvider serviceProvider)
			: base(serviceProvider)
		{
			_synchronizer = ServiceProvider.GetService<ISynchronizer>();
		}

		#region Overrides of ActivePartBase

		protected override void ActivateCore()
		{
			if (_synchronizer == null)
				return;
			if (ServiceProvider.GetService<INotificationService>() == null)
				return;

			_startSyncSubscription = _synchronizer.StartSync.Subscribe(StartSync);
			_endSyncSubscription = _synchronizer.EndSync.Subscribe(EndSync);
		}

		protected override void PassivateCore()
		{
			if (_startSyncSubscription != null)
			{
				_startSyncSubscription.Dispose();
				_startSyncSubscription = null;
			}
			if (_endSyncSubscription != null)
			{
				_endSyncSubscription.Dispose();
				_endSyncSubscription = null;
			}
		}

		#endregion

		#region Private Members

		private void StartSync(EventArgs args)
		{
			//ServiceProvider.ShowNotification(
			//    SyncNotificationResources.SyncAuto,
			//    SyncNotificationResources.SyncStart,
			//    NotificationType.Info);
			ServiceProvider.ShowNotification(
                ml.ml_string(1433, "Ручная синхронизация"), //Manual synchronization
                ml.ml_string(1434, "Начата синхронизация"), //Synchronization started
				NotificationType.Info);
		}

		private void EndSync(EndSyncEventArgs args)
		{
			switch (args.Result)
			{
				case SyncResult.Finished:
					if (args.StatisticsContainer.IsEmpty())
						return;

					ServiceProvider.ShowNotification(
                        ml.ml_string(1435, "Синхронизация окончена"), //Synchronization finished
						args.StatisticsContainer.GetFormattedValues(ServiceProvider),
						NotificationType.Info);

					break;

				case SyncResult.Failed:
					ServiceProvider.ShowNotification(
                        ml.ml_string(1436, "Ошибка при синхронизации"), //Error at synchronization
						args.Exception.Message,
						NotificationType.Error);
					break;
			}
		}

		#endregion
	}
}